"""
:Author: Sven Walter <sven.walter@wltr.eu>
:Since: 11.06.2011
"""

import os
import urllib2
from tempfile import NamedTemporaryFile
from datetime import timedelta, datetime


from django.db import models
from django.core.files.base import File


from . import settings



def download(source, target):
    try:
        tfp = open(target, "wb")
        sfp = urllib2.urlopen(source)
        tfp.write(sfp.read())
        sfp.close()
        tfp.close()
        return True
    except urllib2.HTTPError:
        return False


class External(models.Model):
    source = models.URLField("Source")
    name = models.CharField("Name", max_length=100, help_text="File extension "
                            "should match.")
    file = models.FileField(upload_to=settings.EXTERNAL_PATH, editable=False, null=True)
    last_update = models.DateTimeField("Last Update", editable=False, null=True)
    validation_time = models.PositiveIntegerField("Validation Time", help_text=
                                                  "Time in seconds until the "
                                                  "ressource is beeing "
                                                  "reloaded.", default=86400)
    
    def update(self):
        try:
            tmp = NamedTemporaryFile()
            download(self.source, tmp.name)
            self.file.save(self.name, File(tmp), False)
        except urllib2.HTTPError:
            return
        finally:
            tmp.close()
            
        self.last_update = datetime.now()
        self.save()
        
    @property
    def next_update(self):
        if self.last_update is None:
            return datetime.now()
        else:
            return self.last_update + timedelta(seconds=self.validation_time)
        
    @property
    def path(self):
        try:
            path = self.file.path
        except ValueError:
            self.update()
            path = self.file.path
            
        if not os.path.exists(path):
            self.update()
            
        return self.file.path
    
    @property
    def file_exists(self):
        return os.path.exists(self.path)
        
    def __unicode__(self):
        return u"external://%s" % self.name 

